﻿
//

//


using EMSNet.Core.Service;
using Microsoft.AspNetCore.Http;

namespace EMSNet.Service;

/// <summary>
/// 能源字典服务 🧩
/// </summary>
[ApiDescriptionSettings(ServiceConst.GroupName, Order = 100)]
public class EmsDictionaryService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<EmsDictionary> _emsDictionaryRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public EmsDictionaryService(SqlSugarRepository<EmsDictionary> emsDictionaryRep, ISqlSugarClient sqlSugarClient)
    {
        _emsDictionaryRep = emsDictionaryRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询能源字典 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询能源字典")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<EmsDictionaryOutput>> Page(PageEmsDictionaryInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _emsDictionaryRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.pid==input.pid || u.name.Contains(input.Keyword) || u.code.Contains(input.Keyword))
            .WhereIF(input.pid.HasValue, u => u.pid==input.pid)
            .WhereIF(!string.IsNullOrWhiteSpace(input.name), u => u.name.Contains(input.name.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.code), u => u.code.Contains(input.code.Trim()))
            .LeftJoin<EmsDictionary>((u, p) => u.pid == p.Id)
            .Select((u, p) => new EmsDictionaryOutput
            {
                Id = u.Id,
                pid = u.pid,
                pFkDisplayName = $"{p.name}",
                name = u.name,
                code = u.code,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取能源字典详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取能源字典详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<EmsDictionary> Detail([FromQuery] QueryByIdEmsDictionaryInput input)
    {
        return await _emsDictionaryRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加能源字典 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加能源字典")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddEmsDictionaryInput input)
    {
        var entity = input.Adapt<EmsDictionary>();
        return await _emsDictionaryRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新能源字典 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新能源字典")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateEmsDictionaryInput input)
    {
        var entity = input.Adapt<EmsDictionary>();
        await _emsDictionaryRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除能源字典 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除能源字典")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteEmsDictionaryInput input)
    {
        var entity = await _emsDictionaryRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _emsDictionaryRep.FakeDeleteAsync(entity);   //假删除
        //await _emsDictionaryRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除能源字典 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除能源字典")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteEmsDictionaryInput> input)
    {
        var exp = Expressionable.Create<EmsDictionary>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _emsDictionaryRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _emsDictionaryRep.FakeDeleteAsync(list);   //假删除
        //return await _emsDictionaryRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataEmsDictionaryInput input)
    {
        var pidData = await _emsDictionaryRep.Context.Queryable<EmsDictionary>()
            .InnerJoinIF<EmsDictionary>(input.FromPage, (u, r) => u.Id == r.pid)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.name}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "pid", pidData },
        };
    }
    
    /// <summary>
    /// 导出能源字典记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出能源字典记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageEmsDictionaryInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportEmsDictionaryOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "能源字典导出记录");
    }
    
    /// <summary>
    /// 下载能源字典数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载能源字典数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportEmsDictionaryOutput>(), "能源字典导入模板", (_, info) =>
        {
            if (nameof(ExportEmsDictionaryOutput.pFkDisplayName) == info.Name) return _emsDictionaryRep.Context.Queryable<EmsDictionary>().Select(u => $"{u.name}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入能源字典记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入能源字典记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportEmsDictionaryInput, EmsDictionary>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 父Id
                    var pidLabelList = pageItems.Where(x => x.pFkDisplayName != null).Select(x => x.pFkDisplayName).Distinct().ToList();
                    if (pidLabelList.Any()) {
                        var pidLinkMap = _emsDictionaryRep.Context.Queryable<EmsDictionary>().Where(u => pidLabelList.Contains($"{u.name}")).ToList().ToDictionary(u => $"{u.name}", u => u.Id);
                        //pageItems.ForEach(e => {
                        //    e.pid = pidLinkMap.GetValueOrDefault(e.pFkDisplayName ?? "");
                        //    if (e.pid == null) e.Error = "父Id链接失败";
                        //});
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<EmsDictionary>>();
                    
                    var storageable = _emsDictionaryRep.Context.Storageable(rows)
                        //.SplitError(it => it.Item.pid?.Length > 32, "父Id长度不能超过32个字符")
                        .SplitError(it => it.Item.name?.Length > 32, "名称长度不能超过32个字符")
                        .SplitError(it => it.Item.code?.Length > 32, "编码长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
